from pycparser import c_ast, c_generator
import sys
sys.path.extend(['.', '..'])
from c_ast_decl import ASTBuilder
builder = ASTBuilder()

# 创建变量声明
i_decl = c_ast.Decl(
    name='i',
    quals=[],
    storage=[],
    funcspec=[],
    align=0,
    type=c_ast.TypeDecl(
        declname='i',
        quals=[],
        align=0,
        type=c_ast.IdentifierType(['int'])
    ),
    bitsize=0,
    init=c_ast.Constant(type='int', value='0')
)
j_decl = c_ast.Decl(
    name='j',
    quals=[],
    storage=[],
    funcspec=[],
    align=0,
    type=c_ast.TypeDecl(
        declname='j',
        quals=[],
        align=0,
        type=c_ast.IdentifierType(['int'])
    ),
    bitsize=0,
    init=None
)

# 构建嵌套循环
with builder.for_loop(
    init=c_ast.DeclList(decls=[i_decl]),  # for (int i=0; ...)
    cond=c_ast.BinaryOp(op='<', left=c_ast.ID('i'), right=c_ast.Constant(type='int', value='10')),
    step=c_ast.UnaryOp(op='++', expr=c_ast.ID('i'))
):
    # 外层 for 循环体
    builder.add_statement(c_ast.FuncCall(
        name=c_ast.ID('printf'),
        args=c_ast.ExprList([c_ast.Constant(type='string', value='"i=%d\\n"'), c_ast.ID('i')])
    ))
    
    # 内层 while 循环
    with builder.while_loop(
        cond=c_ast.BinaryOp(
            op='!=',
            left=c_ast.ID('j'),
            right=c_ast.Constant(type='int', value='5')
        )
    ):
        builder.add_statement(c_ast.Assignment(
            op='=',
            lvalue=c_ast.ID('j'),
            rvalue=c_ast.BinaryOp(
                op='+',
                left=c_ast.ID('j'),
                right=c_ast.Constant(type='int', value='1')
            )
        ))
        # 条件 continue
        builder.add_statement(c_ast.If(
            cond=c_ast.BinaryOp(
                op='==',
                left=c_ast.ID('j'),
                right=c_ast.Constant(type='int', value='3')
            ),
            iftrue=c_ast.Compound(block_items=[c_ast.Continue()]),
            iffalse=None
        ))
        # 条件 break
        builder.add_statement(c_ast.If(
            cond=c_ast.BinaryOp(
                op='>=',
                left=c_ast.ID('j'),
                right=c_ast.Constant(type='int', value='4')
            ),
            iftrue=c_ast.Compound(block_items=[c_ast.Break()]),
            iffalse=None
        ))

# 生成代码
generator = c_generator.CGenerator()
print(generator.visit(builder.root))